// 这个文件就是聊天的时候会将关联文档引用的代码
import { getDocumentOss } from '@/services/video-service';
import {
  getExtension,
  isSupportedPreviewDocumentType,
} from '@/utils/document-util';
import React, { useEffect, useState } from 'react';

interface IProps extends React.PropsWithChildren {
  link?: string;
  preventDefault?: boolean;
  color?: string;
  documentName: string;
  documentId: string;
  prefix?: string;
}

const getOss = async (document_id: string) => {
  try {
    const res = await getDocumentOss(document_id);
    // console.log('获取的文档信息:', res.data);

    return res.data.data.oss_url;
  } catch (error) {
    // console.error('获取文档失败:', error);
  }
};

const NewDocumentLink = ({
  children,
  link,
  preventDefault = false,
  color = 'rgb(15, 79, 170)',
  documentId,
  documentName,
  prefix = 'file',
}: IProps) => {
  const [nextLink, setNextLink] = useState(link); // 使用状态管理 nextLink
  const extension = getExtension(documentName);
  useEffect(() => {
    const fetchOssLink = async () => {
      if (!link) {
        const ossLink = await getOss(documentId); // 等待 Promise 解析
        // 如果ossLink没有获得值,则使用原知识库中的东西
        if (!ossLink) {
          const knowledgeLink = `/document/${documentId}?ext=${extension}&prefix=${prefix}`;
          setNextLink(knowledgeLink);
          return;
        }
        // console.log('获取的文档信息:', ossLink);
        setNextLink(ossLink);
      }
    };
    fetchOssLink();
  }, [link, documentId]);

  return (
    <a
      target="_blank"
      onClick={
        !preventDefault || isSupportedPreviewDocumentType(extension)
          ? undefined
          : (e) => e.preventDefault()
      }
      href={nextLink}
      rel="noreferrer"
      style={{ color, wordBreak: 'break-all' }}
    >
      {children}
    </a>
  );
};

export default NewDocumentLink;

// origin:  https://1304838316.vod-qcloud.com/ca6b8047vodcq1304838316/29582bcb1397757908710490810/nHL1alHPLi8A.mp4
// T1:      https://1304838316.vod-qcloud.com/a1556defvodtranscq1304838316/29582bcb1397757908710490810/v.f100010.mp4
// T2:      https://1304838316.vod-qcloud.com/a1556defvodtranscq1304838316/29582bcb1397757908710490810/v.f100020.mp4
